package com.mkk.pro.utils

import android.app.Activity
import android.app.Application
import android.os.Bundle
import androidx.annotation.NonNull
import java.util.*

/**
 *decs acticity生命周期管理
 *auther mkk
 *time  14:52
 *date  2021/11/19  14:52
 **/
class ActivityLifecyclerHelper:Application.ActivityLifecycleCallbacks{

    private var mActStack:Stack<Activity>?=null

    init {
        mActStack=Stack()
    }
    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
         addActivity(activity)
    }

    override fun onActivityStarted(activity: Activity) {

    }

    override fun onActivityResumed(activity: Activity) {

    }

    override fun onActivityPaused(activity: Activity) {

    }

    override fun onActivityStopped(activity: Activity) {

    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

    }

    override fun onActivityDestroyed(activity: Activity) {
        removeActiivty(activity)
    }

    fun addActivity(activity: Activity){
        mActStack!!.add(activity)
    }

    fun removeActiivty(activity: Activity){
        mActStack!!.remove(activity)
    }

    fun getCurrentActivity(){
        mActStack!!.lastElement()
    }
    fun getPreActivity(): Activity? {
        var size=mActStack!!.size
        if (size<2) return null
        return mActStack!!.elementAt(size - 2)
    }

    fun finishActivity(activity: Activity){
        if (activity!=null){
            mActStack!!.remove(activity)
            activity.finish()
        }
    }


    /**
     * 结束指定的Activity
     *
     * @param clazz activity的类
     */
    fun finishActivity(@NonNull clazz: Class<out Activity?>) {
        if (mActStack != null) {
            val it: MutableIterator<Activity> = mActStack!!.iterator()
            synchronized(it) {
                while (it.hasNext()) {
                    val activity = it.next()
                    if (clazz.canonicalName == activity.javaClass.canonicalName) {
                        if (!activity.isFinishing) {
                            it.remove()
                            activity.finish()
                        }
                    }
                }
            }
        }
    }

    /**
     * 结束所有Activity
     */
    fun finishAllActivity() {
        if (mActStack != null) {
            var i = 0
            val size: Int = mActStack!!.size
            while (i < size) {
                val activity: Activity = mActStack!!.get(i)
                if (activity != null) {
                    if (!activity.isFinishing) {
                        activity.finish()
                    }
                }
                i++
            }
            mActStack!!.clear()
        }
    }

    /**
     * 退出
     */
    fun exit() {
        finishAllActivity()
    }
}